using UnityEngine;
using System.Collections;

public class BM_MessageHandler
{
	#region Members
	
	private uint		m_uId;
	private bool		m_bEnable;
	private bool		m_bDebugPrint;
	
	private static readonly int 	m_siBaseCapacity = 5;
	protected Queue					m_qReceivedMessages;
	
	private BM_MessageManager	m_rMessageDispatcher = null;
		
	#endregion
	
	#region Properties

	public uint Id
	{
		get { return m_uId; }
		set { m_uId = value; }
	}
	
	public bool Enable
	{
		get { return m_bEnable; }
		set { m_bEnable = value; }
	}
	
	public bool DebugPrint
	{
		get { return m_bDebugPrint; }
		set { m_bDebugPrint = value; }
	}
	
	public bool HasMessages
	{
		get { return (m_qReceivedMessages.Count > 0); }
	}
	
	#endregion
	
	public BM_MessageHandler()
	{
		m_uId = 0;
		m_bEnable = true;
		
		m_qReceivedMessages = new Queue(m_siBaseCapacity);
		m_rMessageDispatcher = BM_MessageManager.Instance();
		
		AddToDispatcher();
	}
	
	public void AddToDispatcher()
	{
		m_rMessageDispatcher.AddListener(this);
	}
	
	public void RemoveFromDispatcher()
	{
		m_rMessageDispatcher.RemoveListener(this);
	}
	
	public void ReceiveMessage(BM_BaseMessage rMessage)
	{
		m_qReceivedMessages.Enqueue(rMessage);
	}
	
	public void SendMessageToOne(BM_MessageHandler rTarget, BM_BaseMessage rMessage)
	{
		m_rMessageDispatcher.RequestSendMessage(rTarget, rMessage, BM_MessageManager.SendType.SEND_TOONE);
		
		if(DebugPrint)
			Debug.Log("SV_MessageHandler.SendMessageToOne() -> " + rMessage.ToString() + " - Time: " + Time.time);
	}
	
	public void SendMessageToAll(BM_BaseMessage rMessage)
	{
		m_rMessageDispatcher.RequestSendMessage(null, rMessage, BM_MessageManager.SendType.SEND_TOALL);
		
		if(DebugPrint)
			Debug.Log("SV_MessageHandler.SendMessageToAll() -> " + rMessage.ToString() + " - Time: " + Time.time);
	}
	
	public void SendMessageToAllButMe(BM_BaseMessage rMessage)
	{
		m_rMessageDispatcher.RequestSendMessage(null, rMessage, BM_MessageManager.SendType.SEND_TOALLBUTME);
		
		if(DebugPrint)
			Debug.Log("SV_MessageHandler.SendMessageToAll() -> " + rMessage.ToString() + " - Time: " + Time.time);
	}
	
	public void CleanMessages()
	{
		m_qReceivedMessages.Clear();
	}
	
	public BM_BaseMessage ReceivedMessageWithID(MessageID eMessageID)
	{
		BM_BaseMessage rRVal = null;
		
		foreach(BM_BaseMessage msg in m_qReceivedMessages)
		{
			if(msg.m_eMessageID == eMessageID)
			{
				if(DebugPrint)
					Debug.Log("SV_MessageHandler.ReceivedMessageWithID() -> " + msg.ToString());
				
				rRVal = msg;
				break;
			}
		}
		
		return rRVal;
	}
	
	public ArrayList ReceivedMessageGroupWithID(MessageID eMessageID)
	{
		ArrayList vRVal = new ArrayList();
		
		foreach(BM_BaseMessage msg in m_qReceivedMessages)
		{
			if(msg.m_eMessageID == eMessageID)
				vRVal.Add(msg);
		}
		
		if(DebugPrint && vRVal.Count > 0)
			Debug.Log("SV_MessageHandler.ReceivedMessageWithID() -> received messages " + eMessageID + " - count: " + vRVal.Count);
		
		return vRVal;
	}
}
